package cn.blnp.net.flowable.boot.customer.flowable.holder;

import cn.blnp.net.flowable.boot.utils.TenantContextHolder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.cfg.multitenant.TenantInfoHolder;

import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <h3>多租户管理扩展支持</h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/6/9 19:26
 */
@Setter
@Getter
@Slf4j
public class MultiTenantInfoHolder implements TenantInfoHolder {

    /**
     *  线程安全的租户列表
     **/
    private CopyOnWriteArrayList<String> tenantList = new CopyOnWriteArrayList<>();

    /**
     *  用于记录当前持有的租户ID信息
     **/
    private static ThreadLocal<String> tenantThreadLocal = new ThreadLocal<>();

    @Override
    public Collection<String> getAllTenants() {
        return tenantList;
    }

    @Override
    public void setCurrentTenantId(String tenantId) {
        tenantThreadLocal.set(tenantId);
        TenantContextHolder.setTenantId(tenantId);
    }

    @Override
    public String getCurrentTenantId() {
        return tenantThreadLocal.get();
    }

    @Override
    public void clearCurrentTenantId() {
        tenantThreadLocal.remove();
        TenantContextHolder.clear();
    }
}
